<template>
  <VPage>
    <template #left>
      <ul class="nav-button">
        <li
          :class="btnActive === item.value ? 'active' : ''"
          v-for="item in btnOptions"
          :key="item.value"
          @click="() => handleToggle(item.value)"
        >
          <svg-icon
            :icon-class="item.value === 1 ? 'menu' : 'btn_button'"
            class="text-[24px] align-middle"
          ></svg-icon>
          <span>{{ item.lable }}</span>
        </li>
      </ul>
      <el-tree
        :data="menuList"
        :props="defaultProps"
        @node-click="handleNodeClick"
        highlight-current
        :expand-on-click-node="false"
        :current-node-key="currentNodeKey"
        node-key="id"
        ref="treeList"
        class="tree"
        :default-expanded-keys="defaultExpanded"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <el-tooltip
              v-if="node.label.length >= 7"
              class="item"
              effect="dark"
              :content="node.label"
              placement="top-start"
            >
              <span class="lable">{{ node.label }}</span>
            </el-tooltip>
            <span class="lable" v-else>{{ node.label }}</span>
            <span class="status" :class="data.status ? '' : 'col_f00'">{{
              data.status_text
            }}</span>
          </span>
        </template>
      </el-tree>
    </template>

    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <el-input
          v-model="form.name"
          placeholder="名称"
          prefix-icon="search"
          clearable
          style="width: 260px"
        />
        <el-select
          v-model="form.status"
          placeholder="状态"
          style="width: 90px"
          clearable
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </template>
      <template #toolbar_btns>
        <el-button type="primary" @click="handleAdd(null)"
          ><SvgIcon icon-class="Plus" class="text-[12px] mr-[6px]"/>新增</el-button
        >
      </template>
    </VTable>
    <add
      :id="idAdd"
      :menuList="menuList"
      @close="idAdd = ''"
      ref="addRef"
      @refresh="refreshAdd"
    />
    <VRoleManage
      v-model="roleVisible"
      :data="roleData"
      :api="roleApi"
      @close="roleData = {}"
      @refresh="refresh"
    ></VRoleManage>
    <UserManage
      v-model="userVisible"
      :data="userData"
      :api="userApi"
      @close="userData = {}"
      @refresh="refresh"
    ></UserManage>
    <BusinessLog
      dialog
      v-model="logVisible"
      tag="menu"
      :autoLoad="false"
      :business_id="logId"
      @close="logId = ''"
    />
  </VPage>
</template>
<script setup name="List" lang="jsx">
import SvgIcon from "@/components/SvgIcon/index.vue";
import { getMenus } from "@/api/menu";
import {
  getMenusList,
  create,
  deMenu,
  setStatus,
  getData,
  setData,
  getMenuRole,
  setMenuRole,
  getMenuUser,
  setMenuUser,
} from "./api";
import { btnOptions, defaultProps } from "./data.js";
import { statusOptions } from "@/data/index.js";
import { ElMessage } from "element-plus";
import { copyText } from "@/utils/tools.js";
import add from "./add/index.vue";
import VRoleManage from "@/components/VRoleManage";
import UserManage from "./components/userManage/index";
import api from "../attribute/api";
import { userSysAuthList } from "@/Auth/userSys.js";
import { isPermission } from "@/hooks/permission.js";
import BusinessLog from "@/components/BusinessLog/index.vue";
const { proxy } = getCurrentInstance();
const tableOptins = reactive({
  formConfig: {
    data: {
      type: 1,
      name: "",
      status: "",
      menu_id: "",
    },
  },
  columns: [
    { field: "id", title: "ID", width: "60" },
    { field: "sort", title: "排序", width: "60" },
    { field: "name", title: "名称", minWidth: "100" },
    { field: "parent_text", title: "上级目录", width: "120" },
    {
      field: "unique_key",
      title: "唯一标识",
      minWidth: "100",
      slots: {
        default: ({ row }) => {
          return (
            <div class="flex items-center">
              {row.unique_key ? (
                <i
                  class="align-middle cursor-pointer hover:text-[#64a4ff] mr-[4px]"
                  onClick={() => copyText(row.unique_key)}
                >
                  <svg-icon icon-class="copy" class="text-[16px]" />
                </i>
              ) : (
                ""
              )}
              <span>{row.unique_key}</span>
            </div>
          );
        },
      },
    },
    {
      field: "url",
      title: "URL",
      minWidth: "200",
      slots: {
        default: ({ row }) => {
          return (
            <div class="flex items-center">
              <i
                class="align-middle cursor-pointer hover:text-[#64a4ff] mr-[4px]"
                onClick={() => copyText(row.url)}
              >
                <svg-icon icon-class="copy" class="text-[16px]" />
              </i>
              <span>{row.url}</span>
            </div>
          );
        },
      },
    },
    { field: "type_text", title: "类型", width: "100" },
    {
      field: "status_text",
      title: "状态",
      width: "100",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <el-switch
                v-model={row.status}
                active-value={1}
                inactive-value={0}
                onChange={() => handleSwitch(row)}
              ></el-switch>
            </div>
          );
        },
      },
    },
    {
      field: "create_user_text",
      title: "创建人",
      width: "200",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <p class="text-[var(--base-text-color)]">
                {row.create_user_text}
              </p>
              <p class="text-[var(--base-sub-text-color)]">{row.create_time}</p>
            </div>
          );
        },
      },
    },
    {
      title: "操作",
      fixed: "right",
      width: "310",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <el-button link type="primary" onClick={() => handleAdd(row)}>
                编辑
              </el-button>
              <el-divider direction="vertical" />
              <el-button type="danger" link onClick={() => handleDelete(row)}>
                删除
              </el-button>
              <el-divider direction="vertical" />
              {!row.has_child && (
                <>
                  {isPermission([userSysAuthList.list.manage_roles]) && (
                    <el-button
                      type="primary"
                      onClick={() => handleRoleManage(row)}
                      link
                    >
                      分配角色
                    </el-button>
                  )}
                  <el-divider direction="vertical" />
                  {isPermission([userSysAuthList.list.manage_people]) && (
                    <el-button
                      type="primary"
                      onClick={() => {
                        handleUesrManage(row);
                      }}
                      link
                    >
                      分配人员
                    </el-button>
                  )}
                </>
              )}
              <el-button link type="primary" onClick={() => handleLog(row.id)}>
                日志
              </el-button>
            </div>
          );
        },
      },
    },
  ],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => {
        const promiseData = getMenusList({ ...form, ...page });
        tableOptins.formConfig.data.menu_id = "";
        return promiseData;
      },
    },
  },
});
const menuList = ref([]);
const btnActive = ref(1);
const defaultExpanded = ref([]);
onMounted(() => {
  handleToggle(1);
});
const tableRef = ref();
//更新表格数据
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
// 第一次请求不加载表格树
const handleToggle = async (val) => {
  await getMenusData(val);
  nextTick(() => {
    treeList.value.setCurrentKey(currentNodeKey.value);
  });
};
const noLoadTable = ref(false);
const getMenusData = async (type, menu_id = "") => {
  btnActive.value = type;
  tableRef?.value?.setFormField("type", type);
  tableRef?.value?.setFormField("menu_id", menu_id);
  await getMenus({ type: type }).then((res) => {
    menuList.value = res.data;
  });
  if (noLoadTable.value) {
    refresh();
  }
  noLoadTable.value = true;
};
const currentNodeKey = ref("");
const menuStatus = ref(null);
const treeList = ref();
const menuUrl = ref("");
const handleNodeClick = (data) => {
  menuStatus.value = data.status;
  tableRef?.value?.setFormField("menu_id", data.id);
  defaultExpanded.value = [data.id];
  currentNodeKey.value = data.id;
  menuUrl.value = data.url;
  refresh();
  nextTick(() => {
    treeList.value.setCurrentKey(data.id);
  });
};
const idAdd = ref(null);
const menuStatusAdd = ref(null);
const addRef = ref();
const handleAdd = (val) => {
  idAdd.value = val?.id;
  menuStatusAdd.value = val?.status || menuStatus.value;
  addRef.value?.open({
    id: idAdd.value,
    menuStatus: menuStatusAdd.value,
    type: btnActive.value,
    url: menuUrl.value,
    pid: val?.pid || currentNodeKey.value,
  });
};

const refreshAdd = async () => {
  await getMenusData(btnActive.value, currentNodeKey.value);
  nextTick(() => {
    treeList.value.setCurrentKey(currentNodeKey.value);
  });
};
const handleSwitch = async (row) => {
  try {
    const { code, message } = await setStatus({ id: row.id });
    if (code !== 200) {
      ElMessage.warning(message);
      row.status = row.status ? 0 : 1;
      return;
    }
    ElMessage.success("更新成功!");
  } catch (error) {}
};
const handleDelete = (row) => {
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认删除选中的
        <span class="text-[#3366F1] px-[4px]">1</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          await deMenu({ id: row.id });
          ElMessage.success("操作成功");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          if (row.pid !== currentNodeKey.value) {
            await getMenusData(btnActive.value, row.pid);
            nextTick(() => {
              treeList.value.setCurrentKey(currentNodeKey.value);
            });
          } else {
            currentNodeKey.value = null;
            await getMenusData(btnActive.value);
          }
        }
      } else {
        done();
      }
    },
  });
};
//角色管理
const roleData = ref({});
const roleVisible = ref(false);
const roleApi = ref("");
const handleRoleManage = async (val) => {
  const { data } = await getMenuRole({ id: val.id });
  roleData.value = {
    roletitle: val.name,
    roleType: "分类",
    roleData: data?.role_ids || [],
    parmas: { id: val.id, nav_type: val.type },
  };
  roleApi.value = setMenuRole;
  roleVisible.value = true;
};
//人员管理
const userData = ref({});
const userVisible = ref(false);
const userApi = ref("");
const handleUesrManage = async (val) => {
  const { data } = await getMenuUser({ id: val.id });
  userData.value = {
    userData: data || {},
    parmas: { id: val.id, nav_type: val.type },
  };
  userApi.value = setMenuUser;
  userVisible.value = true;
};
const logId = ref("");
const logVisible = ref(false);
const handleLog = (id) => {
  logId.value = id;
  logVisible.value = true;
};
</script>
<style lang="scss" scoped>
.nav-button {
  overflow: hidden;
  display: flex;
  border: 1px solid var(--base-border-color);
  line-height: 32px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  color: var(--base-text-color);
  width: 180px;
  margin: 10px auto 0;
  background-color: var(--base-small-bg-color);

  li {
    flex: 1;
    align-items: center;
    display: flex;
    justify-content: center;
    vertical-align: middle;
    border-radius: 4px;
    margin: 2px;

    img {
      width: 16px;
      height: 16px;
      align-self: center;
    }

    &.active {
      background: #3188ff;
      color: #fff;
    }
  }
}
.tree {
  width: 100%;
  margin-top: 5px;
  &:deep(.el-tree-node) {
    margin: 12px 0;
  }
  .custom-tree-node {
    display: flex;
    justify-content: space-between;
    vertical-align: middle;
    width: 100%;
    span {
      align-self: center;
    }
    .lable {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      width: 100px;
    }
    .status {
      font-size: 12px;
      color: #cdcfd4;
    }
  }

  &:deep(.el-tree-node__content) {
    padding-right: 10px;
  }
}
:deep(.el-tree-node__label) {
  color: #3a4259;
  font-size: 14px;
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: var(--base-menu-bg-color) !important;
  .lable {
    color: #3188ff !important;
  }
}
.col_f00 {
  color: #ff0000 !important;
}
</style>
